//
//  RSComposePictrueView.swift
//  RSWeibo
//
//  Created by Macx on 16/8/19.
//  Copyright © 2016年 Macx. All rights reserved.
//

import UIKit

// cell 的复用标识
private let CellWithReuseIdentifier = "CellWithReuseIdentifier"

class RSComposePictrueView: UICollectionView {
    
    // 调用图片拾取器的闭包
    var pickerImageClosure: (()->())?
    
    // 存储照片的数组
    lazy var picArr: [UIImage] = [UIImage]()
    
//    lazy var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        // 不使用外界传进来的 layout, 使用内部创建的
        let flowlayout = UICollectionViewFlowLayout()
        
        super.init(frame: frame, collectionViewLayout: flowlayout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 计算item的大小
        let itemMargin: CGFloat = 5
        let itemWidth = (frame.size.width - 2 * itemMargin) / 3
        let itemHeight = itemWidth
        
        // 获取布局
        let flowlayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        flowlayout.itemSize = CGSizeMake(itemWidth, itemHeight)
        // 设置间距
        // 水平间距
        flowlayout.minimumInteritemSpacing = itemMargin
        // 垂直间距
        flowlayout.minimumLineSpacing = itemMargin
    }
    
    
    // 设置界面
    private func setupUI(){
        
        // 默认状态下是隐藏的
        hidden = true
        
        // 设置数据源代理
        dataSource = self
        delegate = self
    
        // 注册cell
        registerClass(RSComposeCell.self, forCellWithReuseIdentifier: CellWithReuseIdentifier)
    }
    
    // 往图片数组中添加图片的方法
    func appendToPicArr(image: UIImage) {
        
        // 判断, 当图片到9张得时候, 就不要再添加le
        if picArr.count > 9 {
        
            return
        }
        
        // 添加图片的时候就显示出来配图匡
        hidden = false
    
        picArr.append(image)
        
        // 更新数据
        self.reloadData()
        
//        print(picArr.count)
    }

}

/*
 
 代理数据源方法
 */
extension RSComposePictrueView: UICollectionViewDataSource, UICollectionViewDelegate{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if picArr.count == 0 || picArr.count == 9 {
            return picArr.count
        }else{
        
            return picArr.count + 1
        }
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellWithReuseIdentifier, forIndexPath: indexPath) as! RSComposeCell
        
        // 判断, 
        if indexPath.item == picArr.count {
            cell.image = nil
            // 把删除按钮隐藏
            cell.deleteBtn.hidden = true
        }else{
        
            cell.image = picArr[indexPath.row]
            // 把删除按钮显示出来
            cell.deleteBtn.hidden = false
            
            // 定义删除图片的闭包, 这里的闭包会形成循环引用
            cell.deleteClousure = { [weak self] in
            
                self!.picArr.removeAtIndex(indexPath.item)
                // 删到最后一张的时候, 就配图框隐藏起来
                if indexPath.item == 0{
                
                    self?.hidden = true
                }
                
                // 删除之后刷新数据
                self!.reloadData()
            }
        }
        
        return cell
    }
    
    // 点击某一行的时候调用的方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 如果索引等于数组个数, 就说明是最后一个cell
        if indexPath.item == picArr.count {
            // 取消选中状态
            collectionView.deselectItemAtIndexPath(indexPath, animated: true)

            // 执行 调出图片拾取器的闭包, 弹出图片拾取器
            pickerImageClosure!()
        }
    }
    
}

/*
 直接在这里定义一个cell的类
 */

class RSComposeCell: UICollectionViewCell{
    
    // 删除图片的闭包
    var deleteClousure: (()->())?
    
    // 图片框
    private lazy var imgView: UIImageView = UIImageView()
    
    // 删除按钮
    private lazy var deleteBtn: UIButton = {
    
        let button = UIButton()
        //  添加点击事件
        button.addTarget(self, action: "deleteButtonAction", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        return button
    }()
    
    // 图片
    var image: UIImage? {
    
        didSet{
        
            if image == nil {
                // 设置成加号图片
                imgView.image = UIImage(named: "compose_pic_add")
                //  添加高亮图片
                imgView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                // 把删除按钮隐藏
                deleteBtn.hidden = true
            }else{
            
                // 绑定图片
                imgView.image = image
                // 显示删除按钮
                deleteBtn.hidden = false
                
                // 取消高亮图片
                imgView.highlightedImage = nil
                
            }
        }
    }


    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupCellUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 设置界面
    private func setupCellUI(){
    
        // 把图图片框添加到父控件中
        addSubview(imgView)
        addSubview(deleteBtn)
        
        // 设置约束
        imgView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        deleteBtn.snp_makeConstraints { (make) in
            make.top.equalTo(contentView)
            make.trailing.equalTo(contentView)
            
        }
    }
    
    // 点击删除按钮的方法
    @objc private func deleteButtonAction(){
    
        // 执行删除图片的闭包
        deleteClousure!()
        
    }
    
}




















